package com.activiti.config;

import java.beans.PropertyVetoException;
import java.io.IOException;

import javax.sql.DataSource;
import org.activiti.spring.SpringProcessEngineConfiguration;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
 * activiti数据源配置
 * @author 0380009081
 *
 */
@Configuration
@PropertySource("classpath:com/activiti/config/activitiConfig.properties")
public class ActivitiConfiguration {

	@Value("${activiti.jdbc.driver}")
	private String driver;
	@Value("${activiti.jdbc.url}")
	private String url;
	@Value("${activiti.jdbc.username}")
	private String username;
	@Value("${activiti.jdbc.password}")
	private String password;
	@Value("${activiti.jdbc.maxIdel}")
	private int maxIdel;


	@Bean("activitiDataSource")
	public DataSource dataSource() {
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		try {
			dataSource.setDriverClass(driver);
		} catch (PropertyVetoException e) {
			e.printStackTrace();
		}
		dataSource.setMaxPoolSize(3);
		dataSource.setInitialPoolSize(1);
		dataSource.setJdbcUrl(url);
		dataSource.setUser(username);
		dataSource.setPassword(password);
		dataSource.setMaxIdleTime(maxIdel);
		return dataSource;
	}
	@Bean("activitiPlatformTransactionManager")
	public PlatformTransactionManager annotationDrivenTransactionManager(
			@Qualifier("activitiDataSource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean("springProcessEngineConfiguration")
	public SpringProcessEngineConfiguration springProcessEngineConfiguration(
			@Qualifier("activitiDataSource") DataSource dataSource,@Qualifier("activitiPlatformTransactionManager") PlatformTransactionManager platformTransactionManager) {
		SpringProcessEngineConfiguration spec = new SpringProcessEngineConfiguration();
		spec.setDataSource(dataSource);
		spec.setTransactionManager(platformTransactionManager);
		spec.setDatabaseSchemaUpdate("true");
		Resource[] resources = null;
		// 启动自动部署流程
		try {
			resources = new PathMatchingResourcePatternResolver().getResources("classpath*:process/*.bpmn");
		} catch (IOException e) {
			e.printStackTrace();
		}
		spec.setDeploymentResources(resources);
		return spec;
	}
}
